package com.chuangsi.common.utils;

import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.WritableRaster;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.UUID;

/**
 * ImageUtil
 *
 * @author yx
 * @date 2019/12/10 9:22
 */
public class ImageUtil {

    public static final java.util.List<String> PICSUFFIX = Arrays.asList("jpg","jpeg","png","gif","tiff","raw","bmp");


    public static boolean needCompression(MultipartFile file){
        String fileName = file.getOriginalFilename();
        //获取文件格式
        int lastIndex = fileName.lastIndexOf('.');
        String suffix = "";
        if (lastIndex > 0) {
            suffix = fileName.substring(lastIndex);
        }
        if(PICSUFFIX.contains(suffix.toLowerCase().replace(".",""))){
            double fileSizeMB = file.getSize() / (1024.0 * 1024.0); // 转换为MB
            if(fileSizeMB > 1){
                return true;
            }
        }
        return false;
    }


    /**
     *  等比例缩放
     * @param srcImg        原图
     * @param destImg       目标保存位置
     * @param proportion    压缩比例
     */
    public static  String  zoomImage(File srcImg, String destImg,Double proportion){
        File exist = exist(srcImg, destImg);
        reSize(srcImg,exist,null,null,proportion);
        return exist.getName()
                ;
    }

    /**
     *固定长度缩放
     * @param srcImg   原图
     * @param destImg  目标保存位置
     * @param width    期望宽带
     * @param height    期望长度
     */
    public static  String  zoomImage(File srcImg, String destImg,Integer width,Integer height){
        File exist = exist(srcImg, destImg);
        reSize(srcImg, exist, width, height, null);
        return exist.getName();
    }

    public static File exist(File srcImg, String destImg) {
        if (srcImg == null) {
            return null;
        }
        String fix = null;
        String name = srcImg.getName();
        int i = name.indexOf(".");
        if (i > 0) {
            fix = name.substring(i);
        }
        name = UUID.randomUUID().toString() + fix;
        File file = new File(destImg + name);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        return file;
    }
    /**
     * @param srcImg     原图片
     * @param destImg    目标位置
     * @param width      期望宽
     * @param height     期望高
     * @param proportion 等比例(0.01-1)(等比例不为空是等比例优先)
     */
    public static void reSize(File srcImg, File destImg, Integer width, Integer height, Double proportion) {
        String type = getImageType(srcImg);
        if (type == null) {
            return;
        }
        BufferedImage srcImage = null;
        try {
            srcImage = ImageIO.read(srcImg);
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }
        if (srcImage != null) {
            // targetW，targetH分别表示目标长和宽
            BufferedImage target = null;
            Double sx = null;
            Double sy = null;
            // 等比缩放
            if (proportion!=null) {
                sx = sy = proportion;
                width = (int) (sx * srcImage.getWidth());
                height = (int) (sy * srcImage.getHeight());
            }else{
                sx= (double) width / srcImage.getWidth();
                sy=(double) height / srcImage.getHeight();
            }
            ColorModel cm = srcImage.getColorModel();
            WritableRaster raster = cm.createCompatibleWritableRaster(width, height);
            boolean alphaPremultiplied = cm.isAlphaPremultiplied();
            target = new BufferedImage(cm, raster, alphaPremultiplied, null);
            Graphics2D g = target.createGraphics();
            g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
            g.drawRenderedImage(srcImage, AffineTransform.getScaleInstance(sx, sy));
            g.dispose();
            // 将转换后的图片保存
            try {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                ImageIO.write(target, type, baos);
                FileOutputStream fos = new FileOutputStream(destImg);
                fos.write(baos.toByteArray());
                fos.flush();
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 获取文件后缀不带.
     *
     * @param file 文件后缀名
     * @return
     */
    public static String getImageType(File file) {
        if (file != null && file.exists() && file.isFile()) {
            String fileName = file.getName();
            int index = fileName.lastIndexOf(".");
            if (index != -1 && index < fileName.length() - 1) {
                return fileName.substring(index + 1);
            }
        }
        return null;
    }

}